package com.example.openim.controller;

import com.example.openim.dto.PushRequestDto;
import com.example.openim.service.PushDataService;
import com.example.openim.utils.AjaxResult;
import com.example.openim.utils.Md5Utils;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;

/**
 * @description:
 * @author: xhq
 * @create: 2025-11-03 16:57
 */
@RestController
@RequiredArgsConstructor
@Slf4j
@RequestMapping("/api/ou")
public class PushDataController {

    private final PushDataService pushDataService;

    @Value("${PUSH.SECRET}")
    public String SECRET;

    @Autowired
    private Md5Utils md5Utils;

    @PostMapping("/mdg/push")
    public ResponseEntity<String> push(@RequestBody PushRequestDto dto, HttpServletRequest request) {
        if (dto == null || dto.getRoot() == null){
            return ResponseEntity.badRequest().body("数据不能为空");
        }
        // 异步处理，不阻塞
        pushDataService.processPushData(dto, request);
        return ResponseEntity.ok().build(); // 立即返回
    }

    /**
     * 注册兜底接口
     * @return
     */
    @GetMapping("/fallback-register")
    public AjaxResult triggerFallbackRegister() {
        pushDataService.fallbackRegisterUnregisteredUsers();
        return AjaxResult.success("手动注册调用成功，详细信息请查看日志输出信息");
    }


    /**
     * 获取秘钥
     */
    @PostMapping("/test")
    public AjaxResult test() {
        HashMap<String, Object> map = new HashMap<>();
        long l = System.currentTimeMillis();
        String s1 = SECRET + l;
        String s = md5Utils.lowMD5_32(s1);
        map.put("timestamp", l);
        map.put("secret", SECRET);
        map.put("frontEncData", s1);
        map.put("afterEncData", s);
        return new AjaxResult(map);
    }


}
